package com.itboye.jigongbao.fragments

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.itboye.jigongbao.R
import com.itboye.jigongbao.activity.JiYiBiActivity
import com.itboye.jigongbao.activity.JiYiBiListActivity
import com.itboye.jigongbao.app.MyApplication
import com.itboye.jigongbao.base.BaseFragment
import com.itboye.jigongbao.bean.JiYiBiBean
import com.itboye.jigongbao.bean.MonthAccountBean
import com.itboye.jigongbao.retrofit.base.ResultEntity
import com.itboye.jigongbao.retrofit.presenter.UserPrestener
import com.itboye.jigongbao.utils.ByTimeUtils.timeFormat
import com.itboye.jigongbao.utils.Const
import com.itboye.jigongbao.utils.SPUtils
import com.itboye.jigongbao.utils.TitleBarUtils
import com.itboye.jigongbao.utils.ToastUtil.ByAlert
import com.itboye.jigongbao.widget.MyCalendarView
import com.itboye.jigongbao.widget.MyDatePickerDialog
import kotlinx.android.synthetic.main.actionbar_trans.*
import kotlinx.android.synthetic.main.fragment_index.*
import org.json.JSONObject
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by Administrator on 2017/11/28.
 */
@SuppressLint("ValidFragment")
class IndexFragment(private val index: Int) : BaseFragment(), Observer, MyCalendarView.OnItemClickListener {
    override fun OnItemClick(date: Date?) {
//        ByAlert.alert(date.toString())
        var intent = Intent(activity, JiYiBiListActivity::class.java)
        intent.putExtra("date", timeFormat("yyyyMMdd", date!!.time))
        startActivity(intent)
    }

    private var ar: ArrayList<JiYiBiBean.JiYiBiEntity>? = null

    //    var ar = List<JiYiBiBean.JiYiBiEntity>()
    override fun update(p0: Observable?, p1: Any?) {
        var entity: ResultEntity = p1 as ResultEntity
        if (entity.code != 0) {
            ByAlert.alert(p1.msg)
        } else {
            when (entity.eventType) {
                UserPrestener.By_JgbRecord_workerIndex_Success -> {
                    var ar = entity.data as ArrayList<MonthAccountBean>
                    //测试日期
//                    var bean = MonthAccountBean()
//                    bean.day = "20171231"
//                    ar.add(bean)
//                    bean = MonthAccountBean()
//                    bean.day = "20180202"
//                    ar.add(bean)
                    calendarView.setUserAccountData(ar, true)
                }
                UserPrestener.By_JgbRecord_workerIndex_Fail -> {
                }
                UserPrestener.By_JgbRecord_queryWorker_Success -> {
                    var jiyiBiBean = entity.data as JiYiBiBean
                    ar = jiyiBiBean.list
                    var model: JiYiBiBean.JiYiBiEntity? = null
                    when (ar!!.size <= 0) {
                        true -> {
                            txt_status!!.setText("未记")
                            txt_status!!.setTextColor(resources.getColor(R.color.gallery_red))
                        }
                        else -> {
                            var flag = false

                            run breaking@ {
                                ar!!.forEachIndexed { index, jiYiBiEntity ->
                                    if (jiYiBiEntity.item_type_key.equals("00S002002")) {
                                        flag = true
                                        model = jiYiBiEntity
                                        return@breaking
                                    }
                                }
                            }
                            if (!flag) {
                                run breaking@ {
                                    ar!!.forEachIndexed { index, jiYiBiEntity ->
                                        if (jiYiBiEntity.item_type_key.equals("00S002003")) {
                                            flag = true
                                            model = jiYiBiEntity
                                            return@breaking
                                        }
                                    }
                                }
                            }
                            if (!flag) {
                                txt_status!!.setText("未记")
                                txt_status!!.setTextColor(resources.getColor(R.color.gallery_red))
                            } else {
                                when (model!!.audit_status) {
                                    0 -> {
                                        //待审核
                                        txt_status!!.setText("待审查")
                                        txt_status!!.setTextColor(context!!.resources.getColor(R.color.gallery_red))
                                    }
                                    1 -> {
                                        //审核通过
                                        txt_status!!.setText("已审查")
                                        txt_status!!.setTextColor(context!!.resources.getColor(R.color.gray_B3))
                                    }
                                    2 -> {
                                        //存疑
                                        txt_status!!.setText("存疑")
                                        txt_status!!.setTextColor(context!!.resources.getColor(R.color.gallery_red))
                                    }
                                    else -> {
                                    }
                                }
                            }
                            run breaking@ {
                                ar!!.forEachIndexed { index, jiYiBiEntity ->
                                    if (jiYiBiEntity.item_type_key.equals("00S002003")) {
                                        flag = true
                                        model = jiYiBiEntity
                                        return@breaking
                                    }
                                }
                            }
                            var extra: JSONObject? = null
                            var hourly_wage = 0.0
                            var normal_worktime = 0
                            var over_worktime = 0
                            var gongrengongzi = 0.0
                            try {
                                extra = JSONObject(model?.extra)
                                if (extra!!.has("hourly_wage")) {
                                    hourly_wage = extra!!.getDouble("hourly_wage") / 100
                                }
                                if (extra.has("normal_worktime")) {
                                    normal_worktime = extra.getInt("normal_worktime")
                                }
                                if (extra.has("over_worktime")) {
                                    over_worktime = extra.getInt("over_worktime")
                                }
                                gongrengongzi = hourly_wage * (normal_worktime / 8 + over_worktime / 6)
                                initTopTextValue(normal_worktime, gongrengongzi, over_worktime)
                            } catch (e: Exception) {

                            }
                        }
                    }
                }
                UserPrestener.By_JgbRecord_queryWorker_Fail -> {
                    ByAlert.alert(p1.toString())
                }
                UserPrestener.By_JgbRecord_overseerIndex_Success -> {
                    var ar = entity.data as ArrayList<MonthAccountBean>
                    //测试日期
//                    var bean = MonthAccountBean()
//                    bean.day = "20171231"
//                    ar.add(bean)
//                    bean = MonthAccountBean()
//                    bean.day = "20180202"
//                    ar.add(bean)
                    calendarView.setUserAccountData(ar, false)
                }
                UserPrestener.By_JgbRecord_overseerIndex_Fail -> {

                }
                UserPrestener.By_JgbRecord_queryOverseer_Success -> {
                    var jiyiBiBean = entity.data as JiYiBiBean
                    ar = jiyiBiBean.list
                    var jiezhi = 0.0
                    var jiesuan = 0.0
                    var gongrengongzi = 0.0
                    ar?.forEachIndexed { index, jiYiBiEntity ->
                        //统计今日借支金额
                        if (jiYiBiEntity.item_type_key.equals("00S002004")) {
                            //统计今日结算金额
                            jiezhi += jiYiBiEntity.money / 100
                        } else if (jiYiBiEntity.item_type_key.equals("00S002005")) {
                            //统计工人工资支出
                            jiesuan += jiYiBiEntity.money / 100
                        } else {
                            var extra: JSONObject? = null
                            try {
                                extra = JSONObject(jiYiBiEntity.extra)
                                var hourly_wage = 0.0
                                var normal_worktime = 0
                                var over_worktime = 0
                                var price = 0.0
                                var count = 0

                                if (extra!!.has("hourly_wage")) {
                                    hourly_wage = extra!!.getDouble("hourly_wage") / 100
                                }
                                if (extra!!.has("normal_worktime")) {
                                    normal_worktime = extra!!.getInt("normal_worktime")
                                }
                                if (extra!!.has("over_worktime")) {
                                    over_worktime = extra!!.getInt("over_worktime")
                                }
                                if (extra!!.has("price")) {
                                    price = extra!!.getDouble("price") / 100
                                }
                                if (extra!!.has("count")) {
                                    count = extra!!.getInt("count") / 100
                                }
                                gongrengongzi += (hourly_wage * (normal_worktime / 8 + over_worktime / 6)) + count * price
                            } catch (e: Exception) {

                            }
                        }
                    }

                    initTopTextValue(jiezhi, jiesuan, gongrengongzi)

                }
                UserPrestener.By_JgbRecord_queryOverseer_Fail -> {

                }
                else -> {

                    ByAlert.alert(p1.toString())
                }
            }
        }
    }

    var txt_jiyibi: TextView? = null
    var month_left: ImageView? = null
    var month_right: ImageView? = null
    var userPresenter: UserPrestener? = null
    var calendar: Calendar? = null
    var txt_status: TextView? = null
    var role: String? = null
    var iv_calendar_right: ImageView? = null
    var txt_one: TextView? = null
    var txt_two: TextView? = null
    var txt_three: TextView? = null
    //    var index = IndexFragment@ index
    @SuppressLint("SetTextI18n")
    override fun initData() {
        TitleBarUtils().initTitlebarStyle1(activity, this!!.trans_action_bar_index!!, "今日记账", 0, "", 0, "")
        lay_transroot!!.setBackgroundColor(resources.getColor(android.R.color.transparent))
        role = SPUtils.getSp(Const.ROLE).toString()
        userPresenter = UserPrestener(this)
        initTopTextValue(0.0, 0.0, 0.0)
        initCalendar()

//        txt_jiezhi.text = Html.fromHtml(prefixTitle + title + aftfix)
    }

    private fun initCalendar() {
        calendar = Calendar.getInstance()
        tv_month.setText("${calendar!!.get(Calendar.YEAR)}年${(calendar!!.get(Calendar.MONTH) + 1)}月")
        calendarView.setOnItemClickListener(this)

    }

    override fun onResume() {
        super.onResume()
        todayStatus()
    }

    var today: String? = null
    private fun todayStatus() {
        today = timeFormat("yyyyMMdd", System.currentTimeMillis())
        if (role.equals(Const.FORCEMAN)) {
            userPresenter!!.By_JgbRecord_queryOverseer(null, null, MyApplication.instance!!.loginInfo!!.getMobile(), today, 1, 10, null)
            userPresenter!!.By_JgbRecord_overseerIndex(MyApplication.instance!!.loginInfo!!.getMobile(), activity)
        } else {
            userPresenter!!.By_JgbRecord_queryWorker(null, null, MyApplication.instance!!.loginInfo!!.getMobile(), today, 1, 10, null)
            userPresenter!!.By_JgbRecord_workerIndex(MyApplication.instance!!.loginInfo!!.getMobile(), activity)
        }
//        var todayModel: MonthAccountBean? = null
//
//        run breaking@ {
//            ar.forEachIndexed { index, monthAccountBean ->
//                if (monthAccountBean.day.equals(today)) {
//                    todayModel = monthAccountBean
//                    return@breaking
//                }
//            }
//        }
//        if (todayModel==null) {
//            txt_status!!.setText("未记")
//        }else if(todayModel.get){
//
//        }
    }

    private fun initTopTextValue(value1: Any, value2: Any, value3: Any) {
//        var startPo = 0
//        var endPo1 = ("$value1").length
//        var title1 = "$value1<br/>上班(小时)"
//
//        var title2 = "$value2<br/>加班(小时)"
//        var endPo2 = ("$value2").length
//
//        var title3 = "$value3<br/>收入(元)"
//        var endPo3 = ("$value3").length
        if (role.equals(Const.FORCEMAN)) {
            txt_one!!.setText("借支")
            txt_two!!.setText("结算")
            txt_three!!.setText("工人工资支出")
//            title1 = "$value1<br/>借支"
//            title2 = "$value2<br/>结算"
//            title3 = "$value3<br/>工人工资支出"
        } else {
            txt_one!!.setText("上班(小时)")
            txt_two!!.setText("收入(元)")
            txt_three!!.setText("加班(小时)")
        }
        txt_jiezhi.setText(value1.toString())
        txt_jiesuan.setText(value2.toString())
        txt_zhichu.setText(value3.toString())
//        HtmlTextUtil.setDifferentSizeForTextView(startPo, endPo1, title1, txt_jiezhi)
//        HtmlTextUtil.setDifferentSizeForTextView(startPo, endPo2, title2, txt_jiesuan)
//        HtmlTextUtil.setDifferentSizeForTextView(startPo, endPo3, title3, txt_zhichu)
    }

    override fun onClick(p0: View?) {
        when (p0) {
            txt_jiyibi -> {

                //  var intent = Intent(activity, JiYiBiActivity::class.java)
                var intent = Intent(activity, JiYiBiListActivity::class.java)
                if (ar == null) {
                    ar = ArrayList()
                }
                if (role.equals(Const.FORCEMAN)) {
                    Intent(activity, JiYiBiListActivity::class.java)
                } else {
                    intent = Intent(activity, JiYiBiActivity::class.java)
                    intent.putExtra("type", if (ar!!.size <= 0) {
                        "add"
                    } else {
                        "update"
                    })
                    var flag = false
                    var entitiy: JiYiBiBean.JiYiBiEntity? = null
                    run breaking@ {
                        ar!!.forEachIndexed { index, jiYiBiEntity ->
                            if (jiYiBiEntity.item_type_key.equals("00S002002")) {
                                flag = true
                                entitiy = jiYiBiEntity
                                return@breaking
                            }
                        }
                    }
                    if (ar == null) {
                        intent.putExtra("item_type_key", "00S002003")
                    } else if (ar!!.size <= 0) {
                        intent.putExtra("item_type_key", "00S002003")
                    } else if (flag) {
                        intent.putExtra("item_type_key", "00S002002")
//                        intent.putExtra("model", entitiy)
                        intent.putExtra("id", entitiy!!.id)
                        intent.putExtra("array", ar!!)
                    } else {
                        intent.putExtra("item_type_key", ar!![0].item_type_key)
//                        intent.putExtra("model", ar!![0])
                        intent.putExtra("id", ar!![0].id)
                        intent.putExtra("array", ar!!)
                    }
                }
                startActivity(intent)
            }
            month_left -> {
                tv_month.setText(calendarView.clickLeftMonth())
            }
            month_right -> {
                tv_month.setText(calendarView.clickRightMonth())
            }
            iv_calendar_right -> {
                showDatePickDlg(false, false, true)
            }
            else -> {
            }
        }
    }

    private fun showDatePickDlg(isHideYear: Boolean, isHIdeMonth: Boolean, isHideDay: Boolean) {
        val calendar = Calendar.getInstance()
        val datePickerDialog = MyDatePickerDialog(activity, MyDatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
            var month = "${monthOfYear + 1}"
            if (monthOfYear < 10) {
                month = "0" + "${monthOfYear + 1}"
            } else {

            }
            ByAlert.alert("$year$month")
            tv_month.setText(calendarView.setDate("$year$month"))
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), isHideYear, isHIdeMonth, isHideDay)
        datePickerDialog.show()

    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_index
    }

}
